<?php
$time = sprintf("%.5f", microtime(true));
//session_start(); 
global $cache,$db;
/* memproxy.php */
/* this shit is fast. */
/* ~ Hailey */
/*

--SVN--
$Date: 2008-10-16 06:23:59 +0000 (Thu, 16 Oct 2008) $
$Rev: 12 $
$Author: athnex $
$Id$
*/
require_once('inc/conf.inc.php');

if (isset($_GET['req']))
	$req_key = $_GET['req'];
elseif(isset($_GET['p']))
    $req_key = $_GET['p'];
else
	$req_key = $afDefaultPage;

$header = alwaysGetCache('header');
$footer = alwaysGetCache('footer');
//Get from cache! gogo!
if(!$page = alwaysGetCache($req_key)) {
	//Awsome, lets print it. Generally we want to print html.
	//This will print an array too, so if we needed to do that, we can.
	//But generally we only want html passing through here.
	//And yes, this may not be very safe in terms of injection however
	//I expect anyone who is coding this to understand to not put crazy shit
	//Into memcache. 
    $page = alwaysGetCache('e404'); //This shouldn't ever fail in a properly configured page.
}

if(!isset($_GET['p'])){
    echo $header['html'] . $page['html'] . $footer['html'];
} else {
    print_r($page['html']);
    return;
}

//

//This function will get from cache, if not, it'll request the node, and store in cache.
//It always returns $result['html'] and $result['debug'] if pulled from cache the debug key will store debug information,
//Otherwise it'll simply return 'gen' If gen'd, it will return the rest of the mysql result.

function alwaysGetCache($key,$fresh = 0) {
    global $db,$cache,$bcms,$afdebug,$caTimeout;

    $output = array();

    if($res = $cache->get($key) AND $fresh == 0) {
            //Awsome, we found it.. so lets store the var and return it.
            debug ("cache hit on $key",0);

        foreach ($res as $key => $value) {
            $output[$key] = $value;
        }
        debug($res['debug'],0);
        return $output;
    } else {        //Obviously this object is not in cache.. :(
        if(!isset($bcms)){  //Load bcms if needed..
            $bcms = new bcms();
            debug ('force bcms',0);
        }
        if($bres = $bcms->getNodebyKey($key,$fresh)) {
            debug ("db hit on $key",0);
            //Since we loaded a good ol page, lets store it!
            $cache_data = array('html' => $bres['html'],'debug' => $afdebug);
            $cache->set($key,$cache_data,0,$caTimeout);
            return $bres;
        } else {
            debug ("db miss on $key",1);
            return FALSE;
        }
    }
}

$qtime = sprintf("%.5f", microtime(true)-$time);
debug("Gen in $qtime",0);
?>